<template>
  <l-layout style="background: #f1f2f5" :left="240">
    <template #left>
      <l-panel title="列表关联字段" style="padding: 8px 0 0 0">
        <l-radio class="block-radio" :options="colslist" v-model="config.left.colField"></l-radio>
      </l-panel>
    </template>
    <l-panel title="设置" style="padding: 8px 0 0 4px">
      <el-form style="padding: 16px; maxwidth: 400px" size="mini" ref="form" label-width="80px">
        <el-form-item label="树形标题">
          <el-input v-model="config.left.title"></el-input>
        </el-form-item>
        <div style="text-align: center; margin-bottom: 16px">
          <el-radio-group v-model="config.left.dataType" size="mini" @change="handleDataTypeChange">
            <el-radio-button label="1">静态数据</el-radio-button>
            <el-radio-button label="2">数据字典</el-radio-button>
            <el-radio-button label="3">数据源</el-radio-button>
            <el-radio-button label="4">接口</el-radio-button>
          </el-radio-group>
        </div>
        <!--静态数据-->
        <div v-if="config.left.dataType == 1">
          <el-tree
            ref="tree"
            :data="config.left.options"
            default-expand-all
            draggable
            node-key="value"
            :expand-on-click-node="false"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <span>
                <el-button type="text" size="mini" icon="el-icon-plus" @click="handleNodeAdd(data)"></el-button>
                <!--                <el-button class="warning" type="text" size="mini" icon="el-icon-edit"-->
                <!--                           @click="handleNodeEdit(data)"></el-button>-->
                <el-button
                  class="danger"
                  type="text"
                  size="mini"
                  icon="el-icon-delete"
                  @click="handleNodeRemove(node, data)"
                ></el-button>
              </span>
            </span>
          </el-tree>
          <div style="margin-left: 22px">
            <el-button size="mini" type="text" icon="el-icon-circle-plus-outline" @click="handleParentNodeAdd"
              >添加父级</el-button
            >
          </div>
        </div>
        <!--数据字典-->
        <div v-else-if="config.left.dataType == 2">
          <l-tree-select
            v-model="config.left.dataCode"
            :options="lr_dataItemClassifysTree"
            placeholder="请选择数据字典"
            size="mini"
          >
          </l-tree-select>
        </div>
        <!--远端数据-->
        <div v-else-if="config.left.dataType == 3">
          <el-form-item label="数据源">
            <l-select
              v-model="config.left.dataCode"
              placeholder="请选择数据源"
              size="mini"
              :options="lr_dataSource"
              labelKey="f_Name"
              valueKey="f_Code"
              @change="handleDataSourceChange"
            >
            </l-select>
          </el-form-item>
          <el-form-item label="关联字段">
            <l-select
              v-model="config.left.dataValueKey"
              placeholder="请选择选项关联字段"
              size="mini"
              :options="myColNameList"
            >
            </l-select>
          </el-form-item>
          <el-form-item label="显示字段">
            <l-select
              v-model="config.left.dataLabelKey"
              placeholder="请选择选项显示字段"
              size="mini"
              :options="myColNameList"
            >
            </l-select>
          </el-form-item>
          <el-form-item label="id字段">
            <l-select
              v-model="config.left.dataIdKey"
              placeholder="请选择选项id字段"
              size="mini"
              :options="myColNameList"
            >
            </l-select>
          </el-form-item>
          <el-form-item label="pid字段">
            <l-select
              v-model="config.left.dataPIdKey"
              placeholder="请选择选项父级id字段"
              size="mini"
              :options="myColNameList"
            >
            </l-select>
          </el-form-item>
        </div>
        <!--接口-->
        <div v-else>
          <el-form-item label="选择接口">
            <l-layer-select
              v-model="config.left.dataCode"
              labelKey="f_Name"
              valueKey="f_Id"
              :columns="apiColumns"
              :options="apiArr"
              @change="handleApiChange"
              :loadPageData="loadPageData"
            ></l-layer-select>
          </el-form-item>
          <el-form-item label="选项值">
            <l-select v-model="config.left.dataValueKey" placeholder="请选择选项值" size="mini" :options="apiNameList">
            </l-select>
          </el-form-item>
          <el-form-item label="选项名">
            <l-select
              v-model="config.left.dataLabelKey"
              placeholder="请选择选项显示字段"
              size="mini"
              :options="apiNameList"
            >
            </l-select>
          </el-form-item>
          <el-form-item label="id字段">
            <l-select v-model="config.left.dataIdKey" placeholder="请选择选项id字段" size="mini" :options="apiNameList">
            </l-select>
          </el-form-item>
          <el-form-item label="pid字段">
            <l-select
              v-model="config.left.dataPIdKey"
              placeholder="请选择选项父级id字段"
              size="mini"
              :options="apiNameList"
            >
            </l-select>
          </el-form-item>
        </div>
      </el-form>
    </l-panel>

    <l-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      :height="200"
      @close="closeDialog"
      @ok="handleDialogAdd"
    >
      <div class="l-from-body">
        <el-form :model="dialogForm" size="mini" :rules="dialogRules" ref="dialogForm" label-width="80px">
          <el-form-item label="选项名" prop="label">
            <el-input v-model="dialogForm.label"></el-input>
          </el-form-item>
          <el-form-item label="选项值" prop="value">
            <el-input v-model="dialogForm.value"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </l-dialog>
  </l-layout>
</template>
<script>
export default {
  name: "webcode-lefttree",
  inject: ["formConfig"],
  props: {
    colslist: {
      type: Array,
      default: () => [],
    },
  },
  components: {},
  computed: {
    config() {
      return this.formConfig;
    },
    myColNameList() {
      if (this.config.left.dataCode) {
        const colNameList = this.lr_dataSourceCol[this.config.left.dataCode] || [];
        return colNameList.map((t) => {
          return { value: t, label: t };
        });
      } else {
        return [];
      }
    },
  },
  data() {
    return {
      dialogTitle: "添加选项",
      dialogVisible: false,
      dialogForm: {
        label: "",
        value: "",
      },
      dialogRules: {
        label: { required: true, message: "请输入选项名", trigger: "null" },
        value: { required: true, message: "请输入选项值", trigger: "null" },
      },
      pData: undefined,
      apiNameList: [],
      apiColumns: [
        { label: "数据名称", prop: "f_Name", minWidth: "110" },
        { label: "数据连接", prop: "f_Url", minWidth: "110" },
      ],
      apiArr: [],
    };
  },
  created() {
    this.lr_loadDataItemClassifys();
    this.lr_loadDataSourceList();
    if (this.config.left.dataType == 3) {
      this.lr_loadDataSourceColNames(this.config.left.dataCode);
    }
    this.loadDataSourceCol();
  },
  methods: {
    loadPageData(pageData) {
      return new Promise((resovle) => {
        this.lr_apiListData(pageData).then((res) => {
          this.apiArr = this.$deepClone(this.lr_dataSourceApi["api"]);
          resovle(res);
        });
      });
    },
    handleApiChange(row) {
      this.config.left.dataCode = row.f_Name;
      this.config.left.apiCode = row.f_Id;
      this.config.left.apiUrl = row.f_Url;
      this.config.left.apiResponseType = row.f_ResponseType;
      this.loadDataSourceCol();
    },
    loadDataSourceCol() {
      //解析接口的数据结构
      if (this.config.left.apiResponseType) {
        this.apiNameList = this.turnPropertysInfo(JSON.parse(this.config.left.apiResponseType)).map((item) => ({
          label: item,
          value: item,
        }));
      }
    },
    turnPropertysInfo(responseType) {
      let mainDbTables = [];
      const mainData = responseType.propertysInfo.filter((item) => !item.propertysInfo.length);
      if (mainData.length) {
        //说明对象包含基本类型数据
        mainDbTables = mainData.map((item) => {
          return item.propertyName.toLowerCase();
        });
      }
      const childData = responseType.propertysInfo.filter((item) => item.propertysInfo.length);
      const childDbTables = childData.flatMap((item) => {
        return item.propertysInfo.map((info) => {
          return info.propertyName.toLowerCase();
        });
      });
      return mainDbTables.concat(childDbTables);
    },
    handleDataTypeChange() {
      this.config.left.dataIdKey = "";
      this.config.left.dataPIdKey = "";

      this.config.left.dataCode = "";
      this.config.left.dataValueKey = "";
      this.config.left.dataLabelKey = "";
    },

    handleParentNodeAdd() {
      this.pData = undefined;
      this.dialogTitle = "添加父级选项";
      this.dialogVisible = true;
    },
    handleNodeAdd(data) {
      this.pData = data;
      this.dialogTitle = `添加【${data.label}】的子选项`;
      this.dialogVisible = true;
    },
    handleNodeRemove(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex((d) => d.id === data.id);
      children.splice(index, 1);
    },

    handleDialogAdd() {
      this.$refs.dialogForm.validate((valid) => {
        if (valid) {
          const { label, value } = this.dialogForm;
          const node = this.$refs.tree.getNode(value);
          if (node) this.$message.error("选项值重复");
          else {
            const pData = this.pData;
            const newNode = {
              label,
              value: this.dialogInputType == "number" ? Number(value) : value,
            };
            if (pData) {
              if (!pData.children) this.$set(pData, "children", []);
              pData.children.push(newNode);
            } else {
              this.$set(this.config.left.options, this.config.left.options.length, newNode);
            }
            this.dialogVisible = false;
          }
        }
      });
    },
    closeDialog() {
      this.$refs.dialogForm.clearValidate();
      this.dialogForm = {};
    },

    handleDataSourceChange(val) {
      this.config.left.dataValueKey = "";
      this.config.left.dataLabelKey = "";
      this.config.left.dataIdKey = "";
      this.config.left.dataPIdKey = "";

      if (!this.$validatenull(val)) {
        this.lr_loadDataSourceColNames(val);
      }
    },
  },
};
</script>
<style lang="scss">
.block-radio {
  padding: 8px;
  box-sizing: border-box;
  .el-radio {
    display: block;
    margin-bottom: 8px;
  }
}
</style>

<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
